<?php

namespace App\Logic;

use App\Model\ApplyExpert;
use App\Model\Log;
use App\Model\Project;
use App\Model\User;
use App\Model\UserModelExpert;
use App\Service\EmailService;
use App\Service\SmsService;
use App\Utils\Enum\SceneEnum;
use App\Utils\Enum\UserEnum;
use Exception;
use Hyperf\DbConnection\Db;

class AdminExpertLogic
{
    /**
     * 专家列表
     * @param $input
     * @return array
     */
    public static function listExpert($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = UserModelExpert::query()->when(!empty($input['query']['expertUserNick']), function ($query) use ($input) {
            $userIds = User::query()->where(['role_id' => UserEnum::USER_TYPE_EXPERT, 'nickname' => $input['query']['expertUserNick']])->get(['id'])->pluck('id')->toArray();
            $query->whereIn('userid', $userIds);
        });
        $total = $query->count();
        if ($total) {
            $records = $query->with(['user'])->orderBy('id', 'desc')->offset($offset)->limit($pageSize)->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 专家详情
     * @param $userId
     * @return array
     */
    public static function detailExpert($userId): array
    {
        return UserModelExpert::query()->where('userid', $userId)->with(['user'])->first()->toArray();
    }

    /**
     * 修改专家信息
     * @throws Exception
     */
    public static function editExpert($userId, $input): true
    {
        $expert = UserModelExpert::query()->where('userid', $userId)->first();
        if (empty($expert)) {
            throw new Exception('专家不存在');
        }
        try {
            UserModelExpert::query()->where('id', $expert['id'])->update([
                'introduce' => $input['introduce'],
                'expert_desc' => $input['expertDesc']
            ]);
            return true;
        } catch (Exception $e) {
            Log::error(sprintf('专家信息修改失败:%s', $e->getMessage()));
            throw new Exception('修改失败');
        }
    }

    /**
     * 方案列表
     * @param $input
     * @return array
     */
    public static function listProject($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = Project::query()->when(!empty($input['query']['match_id']), function ($q) use ($input) {
            $q->where('match_id', $input['query']['match_id']);
        })->when(!empty($input['query']['userid']), function ($q) use ($input) {
            $q->where('userid', $input['query']['userid']);
        });
        $total = $query->count();
        if ($total) {
            $records = $query->when($pageSize > 0, function ($q) use ($pageSize, $offset) {
                $q->limit($pageSize)->offset($offset);
            })->orderBy('id', 'desc')->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 申请列表
     * @param $input
     * @return array
     */
    public static function listSettled($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = ApplyExpert::query()->when(isset($input['query']['status']) && $input['query']['status'] != '', function ($q) use ($input) {
            $q->where('audit_status', (int)$input['query']['status']);
        });
        $total = $query->count();
        if ($total) {
            $records = $query->with(['user'])->orderBy('id', 'desc')->offset($offset)->limit($pageSize)->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 审核申请
     * @throws Exception
     */
    public static function auditSettled($id, $input): true
    {
        $info = ApplyExpert::query()->where('id', $id)->first();
        if (!$info) {
            throw new Exception('未找到该申请');
        }
        if ($info['audit_status'] != 0) {
            throw new Exception('该申请已经处理过了');
        }

        $data = [
            'expert_desc' => $input['expertDesc'],
            'audit_status' => $input['status'],
            'audit_mark' => $input['remark'] ?? '',
            'audit_time' => time(),
        ];
        Db::beginTransaction();
        try {
            ApplyExpert::query()->where('id', $id)->update($data);
            if ($input['status'] == 1) {
                User::query()->where('id', $info['userid'])->update([
                    'role_id' => UserEnum::USER_TYPE_EXPERT
                ]);
                UserModelExpert::create([
                    'userid' => $info['userid'],
                    'expert_id' => 0,
                    'expert_desc' => $input['expertDesc'],
                ]);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollBack();
            \App\Utils\Log::error(sprintf('专家入驻申请审核失败:%s', $e->getMessage()));
            throw new Exception('处理失败');
        }

        $user = User::query()->where('id', $info['userid'])->first();
        try {
            if (!empty($user['email'])) {
                EmailService::send($user['mail'], $input['status'] == 1 ? SceneEnum::APPLY_SUCC : SceneEnum::APPLY_FAIL, ['title' => '专家入驻']);
            } else if (!empty($user['mobile'])) {
                SmsService::send($user['mobile'], $input['status'] == 1 ? SceneEnum::APPLY_SUCC : SceneEnum::APPLY_FAIL, ['title' => '专家入驻']);
            }
        } catch (Exception $e) {
            \App\Utils\Log::error(sprintf('专家审核入驻通知异常:%s', $e->getMessage()));
        }
        return true;
    }
}